<!-- 登录组件 -->
<template>
  <div class="login">
    <van-nav-bar
      title="用户登录"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <div class="login-panel"/>
    <van-field
      v-model="userName"
      label="用户名"
      placeholder="请输入用户名"
      required
      :error-message="userNameErrorMsg"
    />
    <van-field
      v-model="password"
      label="密码"
      placeholder="请输入密码"
      required
      :error-message="passwordErrorMsg"
      type="password"
    />
    <div class="captcha-img">
      <van-field
        v-model="captcha"
        label="验证码"
        placeholder="请输入验证码"
        required
        :error-message="captchaMsg"
      />
      <div v-html="imgSrc" class="captcha-div" @click="changeCaptcha" />
    </div>
    <div class="login-button">
      <van-button
        type="primary"
        size="large"
        @click="handleLogin"
        :loading="loginLoading"
      >
        马上登录
      </van-button>
    </div>
    <div class="register-action"><a href="/register">-->前往注册</a></div>
  </div>
</template>

<script>
import axios from 'axios';
// Toast提示不需要使用use()加载
import { Toast } from "vant";
import md5 from 'md5';
import requestUrl from '../../serverApi';

export default {
  data () {
    return {
      userName: '',
      password: '',
      captcha: '',
      captchaFont: '', 
      loginLoading: false,
      userNameErrorMsg: '',
      passwordErrorMsg: '',
      captchaMsg: '',
      imgSrc: '',
    }
  },
  created() {
    // 如果登录过了，直接跳转到首页
    // 获取验证码
    this.getCaptcha();
  },
  methods: {
    onClickLeft() {
      this.$router.go(-1);
    },
    changeCaptcha() {
      // 点击验证码跟新图片
      this.getCaptcha();
    },
    getCaptcha() {
      const cookies = document.cookie;
      if (cookies && cookies.split('=')[1]) {
        Toast('已经登录');
        this.$router.push({name: 'ShoppingMall'});
        return;
      }
      axios.get(requestUrl.getCaptcha).then((res) => {
        const data = res.data;
        if (data.code === 200) {
          this.imgSrc = data.decodeImg;
          this.captchaFont = data.txtValue; // 验证码的字母
        }
      }).catch((err) => {
        console.log(err);
      });
    },
    handleLogin() {
      // 注册用户操作
      this.checkForm() && this.userLogin();
    },
    userLogin() {
      // 注册用户请求
      this.loginLoading = true;
      axios.post(requestUrl.userLogin, {
        userName: this.userName,
        password: md5(this.password),
      }, {
        withCredentials: true,
      }).then((res) => {
        if (res.data.code === 200 && res.data.isMatch) {
          // 保存登录状态
          localStorage.userInfo = JSON.stringify({ userName: this.userName });
          Toast.success(res.data.message);
          this.$router.push('/'); // 暂时先跳转到首页
        } else {
          Toast.fail(res.data.message);
          this.loginLoading = false;
        }
      }).catch((err) => {
        Toast.fail('登录失败');
        this.loginLoading = false;
      })
    },
    checkForm() {
      // 校验提交表单
      let isOk = true;
      if (this.userName.length < 2) {
        this.userNameErrorMsg = '用户名长度不得少于2位';
        isOk = false;
      } else {
        this.userNameErrorMsg = '';
      }
      if (this.password.length < 6) {
        this.passwordErrorMsg = '密码长度不得少于6位';
        isOk = false;
      } else {
        this.passwordErrorMsg = '';
      }
      if (!this.captcha) {
        this.captchaMsg = '验证码不能为空';
        isOk = false;
      } else if(this.captchaFont.toLowerCase() !== this.captcha.toLowerCase()) {
        this.captchaMsg = '填写验证码错误';
        isOk = false;
      } else {
        this.captchaMsg = '';
      }
      return isOk;
    }
  }
}

</script>
<style scoped>
  .login {
    background: #fff;
  }
  .login-panel{
    width:96%;
    border-radius: 5px;
    padding-bottom:50px;
  }
  .login-button{
    padding-top:10px;
  }
  .register-action {
    font-size: 14px;
    text-align: right;
    padding: 10px;
  }
  .captcha-img {
    margin-top: 10px;
    position: relative;
  }
  .captcha-div {
    width: 140px;
    overflow: hidden;
    position: absolute;
    top: -10px;
    right: 0px;
  }
</style>
